package answer

func expand(s string) string {
	if len(s) < 2 {
		return s
	}
	sBytes := []byte(s)
	start, maxLen := 0, 1
	for i := 0; i < len(sBytes)-1; i++ {
		//奇数最大长度
		oddLen := expandAroundCenter(sBytes, i, i)
		//偶数最大长度
		evenLen := expandAroundCenter(sBytes, i, i+1)
		currMaxLen := max(oddLen, evenLen)
		//取代最大长度
		if currMaxLen > maxLen {
			maxLen = currMaxLen
			start = i - (maxLen-1)/2
		}
	}
	return s[start : start+maxLen]
}

/**
 * @Description: 扩散中心位，找中心位的最大长度
 */
func expandAroundCenter(sBytes []byte, left, right int) int {
	i, j := left, right
	for i >= 0 && j < len(sBytes) {
		//能够形成回文串则往外扩
		if sBytes[i] == sBytes[j] {
			i--
			j++
		} else {
			break
		}
	}
	//返回能够扩展的最长回文串长度
	return j - i - 1
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}
